//
//  JZHBlackCardDetailViewController.m
//  极致荟
//
//  Created by mac on 14-4-30.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHBlackCardDetailViewController.h"
#import "JZHTabbarViewController.h"
#import "JZHHouViewController.h"
#import "JZHShare.h"
#import "JZHHowLookMeViewController.h"
#import "JZHHuiFuTableViewCell.h"
#import "JZHDetailsViewController.h"
#import "JZHPersonaldetailsViewController.h"
@interface JZHBlackCardDetailViewController ()
{
    int type;//1=商品详情  0=活动详情
}
@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UITableView *table;
@property (strong, nonatomic) IBOutlet UIView *agview;

@end

@implementation JZHBlackCardDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initCommodity:(id)commodity
{
    self=[[JZHBlackCardDetailViewController alloc]init];
    if(self)
    {
        if([commodity isKindOfClass:[JZHCommodity class]])
        {
            self.commodity=commodity;
            type=1;
        }else
        {
            self.act=commodity;
            type=0;
        }
        
    }
    return self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
   
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self setNavigation];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//导航条设置
-(void)setNavigation
{
    self.navigationItem.title = @"活动详情";
    self.typelable.text=@"报名";
    [self loadHoHttpData];
    
    //设置左侧按钮
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
}

- (void)backAction:(UIButton *)sender
{
    if([UINavigationController miancerr]==1)
    {
        [UINavigationController Pop:self];
    }else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
  
}

- (IBAction)baoming:(id)sender
{
    if(type==1)
    {
        [self.navigationController pushViewController:[[JZHDetailsViewController alloc]init] animated:YES];
        return;
    }
    [MMProgressHUD showWithStatus:@"报名中..."];
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:self.act.actId],@"clubId",[NSNumber numberWithInt:[User defuceUser].userId],@"userId", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"club/addclubJoin") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            [MMProgressHUD dismissWithSuccess:@"报名成功"];
        }else if(rerurncode==-3)
        {
            [MMProgressHUD dismissWithError:@"你已经报名了" afterDelay:1.0];
        }else
        {
            [MMProgressHUD dismissWithError:@"报名失败"];
        }
    }];
    //[[UIApplication sharedApplication].windows[0] addSubview:self.agview];
}

///请求网络数据
- (void)loadHoHttpData
{
   // [MMProgressHUD showWithStatus:@"加载数据中..."];
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt: self.act.actId ],@"clubId" ,nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"club/clubView") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        if(rerurncode==0)
        {
            [MMProgressHUD dismiss];
            NSLog(@"%@",data);
            NSDictionary* datedic=[[data objectForKey:@"data"] objectForKey: @"clubData"];
            self.tilete.text=[datedic objectForKey:@"Subject"];
            self.addsa.text=[datedic objectForKey:@"Address"];
        
            NSDate *date=[NSDate dateWithTimeIntervalSince1970:[[datedic objectForKey:@"clubTime"] longLongValue]];
            NSDateFormatter *form=[[NSDateFormatter alloc]init];
           
            if([[NSDate date] timeIntervalSince1970] >[date timeIntervalSince1970])
            {
                self.bmview.hidden=YES;
            }
            [form setDateFormat:@"hh:mm"];
            self.daytime.text=[form stringFromDate:date];
            [form setDateFormat:@"MM"];
            self.meun.text=[self menunint:[[form stringFromDate:date] intValue]];
            [form setDateFormat:@"dd"];
            self.ciday.text=[form stringFromDate:date];
            [form setDateFormat:@"hh"];
            int timeampm=[[form stringFromDate:date] intValue];
            if(timeampm<=12)
            {
                self.amorpm.text=@"AM";
            }else
            {
                self.amorpm.text=@"PM";
            }
            
            //获取评论信息
            NSMutableArray *muarr=[[NSMutableArray alloc]init];
            for(NSDictionary *comdic in [ [data objectForKey:@"data"]objectForKey:@"commentData"])
            {
                JZHReview *rev=[[JZHReview alloc]init];
                OtherUsers *ouser=[[OtherUsers alloc]init];
                
                ouser.userId=[[comdic objectForKey:@"userID"] intValue];
                ouser.username=[comdic objectForKey:@"userName"];
                ouser.userHeadImage=[[[data  objectForKey:@"data"] objectForKey:@"imgPrefix"] stringByAppendingString:[comdic objectForKey:@"userAvatar"]];
                rev.recUser=ouser;
                rev.comment=[comdic objectForKey:@"content"];
                rev.revdate=[NSDate dateWithTimeIntervalSince1970:[[comdic objectForKey:@"addTime"] longLongValue]];
                [muarr addObject:rev];
            }
            self.act.actcom=muarr;
            
            [self.table reloadData];
            
            [self addimage:[datedic objectForKey:@"Image"] headurl:[[data  objectForKey:@"data"] objectForKey:@"imgPrefix"]];
        
            [self adduserheadimage:[[data objectForKey:@"data"] objectForKey:@"clubJoinData"] heandpath:[[data  objectForKey:@"data"] objectForKey:@"imgPrefix"]];
            [self aoutScorllViewOffesTxt:[datedic objectForKey:@"Detail"]];
        }else
        {
            [MMProgressHUD showInformationWithTips:@"请求失败"];
        }
        
    }];
}

- (IBAction)userliset:(id)sender
{
    if(type==1)
    {
    [self.navigationController pushViewController:[[JZHHowLookMeViewController alloc] initType:3 activit:self.commodity] animated:YES];
    }else
    {
        [self.navigationController pushViewController:[[JZHHowLookMeViewController alloc] initType:4 activit:self.act] animated:YES];
    }
    
}



- (IBAction)shoucang:(id)sender
{
    NSString *footType=@"";
    int footid;
    if(type==1)
    {
        footType=@"topic_content";
        footid=self.commodity.comid;
    }else
    {
        footType=@"club";
        footid=self.act.actId;
    }
    
    NSDictionary *dic=[[NSDictionary alloc]initWithObjectsAndKeys:[NSNumber numberWithInt:[User defuceUser].userId],@"userId", [NSNumber numberWithInt:footid],@"favoriteId",footType,@"favoriteType", nil];
    [HttpRequest httpRequestPost:JZHHTTPURL(@"favorite/addFavorite") parameters:dic block:^(id data, HttpReturnCode rerurncode) {
        [MMProgressHUD showWithStatus:@"收藏中..."];
        if(rerurncode==0)
        {
            [MMProgressHUD dismissWithSuccess:@"收藏成功"];
        }else if(rerurncode==-4){
            [MMProgressHUD dismissWithError:@"你已经收藏了" afterDelay:1.0];
        }else
        {
            [MMProgressHUD dismissWithError:@"收藏失败"];
        }
            
    }];
}

///添加商品图片
- (void)addimage:(NSArray *)arr headurl:(NSString *)head;
{
    
    [_imagescorll setContentSize:CGSizeMake(self.imagescorll.frame.size.width*arr.count, 0)];
    [_page setNumberOfPages:arr.count];
    for(int i=0;i<arr.count;i++)
    {
        NSString *path=[head stringByAppendingString:arr[i]];
        UIImageView *imageview=[[UIImageView alloc]initWithFrame:CGRectMake(i*self.imagescorll.frame.size.width, 0, self.imagescorll.frame.size.width, self.imagescorll.frame.size.height)];
        //[ImageCache imageName:@"3.jpg" UiImageview:imageview];
        [ImageCache imageUrl:path UiImageview:imageview];
        [_imagescorll addSubview:imageview];
    }
    
}

///添加来访人头像
- (void)adduserheadimage:(NSArray *)arr heandpath:(NSString *)head
{
    if(arr.count<1)
    {
        self.userListbut.hidden=YES;
        self.userListLable.hidden=NO;
        return;
    }
    self.userListbut.hidden=NO;
    self.userListLable.hidden=YES;
    for(int i=0;i<arr.count;i++)
    {
        UIImageView *image=[[UIImageView alloc]initWithFrame:CGRectMake(i*35+i*3, 0, 35, 35)];
        image.userInteractionEnabled=YES;
        image.tag=200+[[[arr objectAtIndex:i] objectForKey:@"userID"] intValue];
        [image addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clikchead:)]];
        NSString *path=[head stringByAppendingString:[[arr objectAtIndex:i] objectForKey:@"userAvatar"]];
        [ImageCache imageUrl:path UiImageview:image];
        [self.userheadImageView addSubview:image];
        if(i>6)
        {
            return;
        }
    }
}

- (void)clikchead:(UITapGestureRecognizer *)tap
{
    OtherUsers *user=[[OtherUsers alloc] init];
    user.userId=tap.view.tag-200;
    [self.navigationController pushViewController:[JZHPersonaldetailsViewController shareName:user] animated:YES];
}
///自适应文字高度和条Scorllview偏移量
- (void)aoutScorllViewOffesTxt:(NSString *)txt
{
    [self.comcontent setText:txt];
    [self.comcontent sizeToFit];
    [self.table setFrame:CGRectMake(self.table.frame.origin.x, self.comcontent.frame.origin.y+ self.comcontent.frame.size.height, self.table.frame.size.width, self.table.frame.size.height)];
    [self.view2 setFrame:CGRectMake(self.view2.frame.origin.x, self.view2.frame.origin.y, self.view2.frame.size.width, self.table.frame.size.height+self.comcontent.frame.size.height+self.comcontent.frame.origin.y)];
    [self.mainScorll setContentSize:CGSizeMake(0, self.view.frame.size.height+self.comcontent.frame.size.height+self.table.frame.size.height-100)];
}
- (IBAction)close:(id)sender
{
    [self.agview removeFromSuperview];
}
- (IBAction)ok:(id)sender
{
    [self.agview removeFromSuperview];
}
- (IBAction)puspin:(id)sender
{
    if(type==1)
    {
        [self.navigationController pushViewController:[[JZHHouViewController alloc]initId:self.commodity type:0] animated:YES];

    }else
    {
        [self.navigationController pushViewController:[[JZHHouViewController alloc]initId:self.act type:1] animated:YES];

    }
    

}
- (IBAction)share:(id)sender
{
    JZHShare *share=[[NSBundle mainBundle]loadNibNamed:@"JZHShare" owner:self options:nil][0];
    [share shareData:@"asdf" shareTxt:@"adf" image:nil];
    [share show:1 viewcontroller:self];
}
#pragma mark-------TableView代理----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

{
    int page;
    if(type==1)
    {
        page=self.commodity.rev.count;
    }else
    {
        page=self.act.actcom.count;
    }
    [self.table setFrame:CGRectMake(self.table.frame.origin.x, self.table.frame.origin.y, self.table.frame.size.width, page*60)];
    return page;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *pengyoucell=@"PengyouCell";
    
    JZHHuiFuTableViewCell *cell=[tableView dequeueReusableHeaderFooterViewWithIdentifier:pengyoucell];
    if(!cell)
    {
        cell=[[NSBundle mainBundle]loadNibNamed:@"JZHHuiFuTableViewCell" owner:self options:nil][0];
    }
   
    
     [cell addCellData:self.act.actcom[indexPath.row] viewconteroller:self isHuiFu:NO];
    
   
    return cell;
    
}


#pragma mark----scorllview delete-----
- (void)scrollViewDidScroll:(UIScrollView *)scrollView;
{
    
    CGFloat x=scrollView.contentOffset.x/self.imagescorll.frame.size.width;
    if(fmod (x,1 )==0)
    {
        [_page setCurrentPage:x];
    }
    
}

- (NSString *)menunint:(int)i
{
    NSString *str=@"";
    switch (i) {
        case 1:
            return  str=@"Jan";
            break;
        case 2:
            return  str=@"Feb";
            break;
        case 3:
            return  str=@"Mar";
            break;
        case 4:
            return  str=@"Apr";
            break;
        case 6:
            return  str=@"Jun";
            break;
        case 7:
            return  str=@"Jul";
            break;
        case 8:
            return  str=@"Aug";
            break;
        case 9:
            return  str=@"Sep";
            break;
        case 10:
            return  str=@"Oct";
            break;
        case 11:
            return  str=@"Nov";
            break;
        case 12:
            return  str=@"Dec";
            break;
        default:
            return @"";
            break;
    }
}

@end
